<?php

namespace business\news\services;

use business\news\models\NewsDetailModel;
use business\news\models\NewsModel;
use common\utils\DateTimeUtils;
use common\utils\StringUtils;

class NewsService
{
    /* @var  $defaultPageSize int  默认分页值 */
    private $defaultPageSize = 50;

    /* @var $isSaveAllIndex bool 是否保存所有索引 */
    private $isSaveAllIndex = false;

    public function __construct($submitAllIndex = false)
    {
        $this->createIndex();
        $this->isSaveAllIndex = $submitAllIndex;
    }

    /**
     * 创建索引
     * @return void
     */
    protected function createIndex()
    {
        $model = new \business\elasticsearch\models\NewsModel();
        !$model->existsIndex() && $model->createIndex();
    }


    /**
     * 保存索引
     *
     * @return bool
     */
    public function saveIndex()
    {

        $newsCount = $this->getNewsCount();
        echo  'news index count:'.$newsCount.PHP_EOL;
        if (empty($newsCount)) {
            return true;
        }
        $pageCount = intval(ceil($newsCount / $this->defaultPageSize));
        echo  'news index pageIndex:'.$pageCount.PHP_EOL;
        for ($i = 1; $i <= $pageCount; $i++) {
            $list = $this->listNews($i);

            echo  'news index list:'.$i.PHP_EOL;
            $this->handleNews($list);
        }
        return true;
    }


    /**
     *  校验相关新闻数据
     *
     * @param $list
     * @return array
     */
    private function handleNews($list)
    {
        if (empty($list)) {
            return [];
        }
        foreach ($list as $model) {
            /* @var $model \business\news\models\NewsModel */
            $uid = $model->uid;
            list($categoryIds, $categoryNames) = $this->getCategoryArr($model->category_id);
            $item = [
                'uid'              => $uid,
                'title'            => $model->title,
                'categoryId'       => $categoryIds,
                'categoryName'     => $categoryNames,
                'author'           => $model->author,
                'source'           => $model->source,
                'tag'              => $model->tag,
                'digest'           => $model->digest,
                'imgSrc'           => $model->img_src,
                'content'          => $this->getNewsDetail($uid, true),
                'createdTime'      => DateTimeUtils::ConvertToString($model->create_time)
            ];
            $es_news = \business\elasticsearch\models\NewsModel::findOne($uid);
            if (empty($es_news)) {
                $es_news = new \business\elasticsearch\models\NewsModel();
                $es_news->primaryKey = $uid;
            }
            $es_news->setAttribute($this->handleUpdateSet($item), false);
            $rs = $es_news->save();
            if (!$rs) {
                \Yii::error('update es_news failed! uid:' . $uid);
            }
        }
        return true;
    }

    protected function handleUpdateSet($needUpdateIndex) {
        $updateIndex = [];

        if (!empty($needUpdateIndex)) {
            $updateIndex = $needUpdateIndex;
        }

        return $updateIndex;
    }

    /**
     * 获取新闻详情
     *
     * @param $uid
     * @param bool $filtHtml
     * @return mixed|string
     */
    public function getNewsDetail($uid, $filtHtml = false)
    {
        $model = NewsDetailModel::findOne($uid);
        if (empty($model)) {
            return '';
        }

        if ($filtHtml) {
            return StringUtils::filtHtml($model->detail);
        }
        return $model->detail;
    }

    /**
     * 获取新闻类别对应搜索分类的ID，Names集合
     *
     * @param $categoryCode
     * @return array
     */
    public function getCategoryArr($categoryCode)
    {
        //力扬要求资讯分类只显示当前资讯所在的分类 ---- by donghui
        $sql = <<<SQL
        select category_code , category_name  from b2b_news.category  where category_code = :categoryCode
SQL;
        $categorys = \Yii::$app->getDb()->createCommand($sql, [':categoryCode' => $categoryCode])->queryOne();

        $categoryName = isset($categorys['category_name']) ? $categorys['category_name'] : $categorys['category_name'];
        return [$categoryCode, $categoryName];
    }

    /**
     * 获取索引新闻数量
     *
     * @return int
     */
    private function getNewsCount()
    {

        $query = NewsModel::find()->where(['is_show' => 1]);
        if (!$this->isSaveAllIndex) {
            $query->andWhere('last_modify_time>=:last_modify_time',
                [
                    ':last_modify_time' => $this->getIncreaseMaxTime()
                ]);
        }
        return $query->count();
    }


    /**
     *  获取新闻信息
     *
     * @param $index
     * @return array
     */
    private function listNews($index)
    {
        $query = NewsModel::find()->where(['is_show' => 1]);
        if (!$this->isSaveAllIndex) {
            $query->andWhere('last_modify_time>=:last_modify_time',
                [
                    ':last_modify_time' => $this->getIncreaseMaxTime()
                ]);
        }
        $query->offset(intval($index - 1) * $this->defaultPageSize)->limit($this->defaultPageSize);
        return $query->orderBy(['uid' => SORT_DESC])->all();
    }

    /**
     * 获取增两索引时间区间值，取两小时内有变化数据
     *
     * @return string
     */
    private function getIncreaseMaxTime()
    {
        // 默认增量索引更新2小时内有变化的新闻
        $now = DateTimeUtils::now();
        return DateTimeUtils::ConvertToString(DateTimeUtils::AddMinutes($now, 60 * 2));
    }
}